package com.children.growth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.children.growth.entity.MentalHealth;
import com.children.growth.mapper.MentalHealthMapper;
import com.children.growth.service.MentalHealthService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 心理健康服务实现类
 * 
 * @author children
 * @since 1.0.0
 */
@Service
public class MentalHealthServiceImpl extends ServiceImpl<MentalHealthMapper, MentalHealth> implements MentalHealthService {

    @Override
    public boolean createMentalHealth(MentalHealth mentalHealth) {
        mentalHealth.setCreateTime(LocalDateTime.now());
        mentalHealth.setUpdateTime(LocalDateTime.now());
        return save(mentalHealth);
    }

    @Override
    public Page<MentalHealth> getMentalHealthList(Long userId, Integer pageNum, Integer pageSize, String warningLevel, String startDate, String endDate) {
        Page<MentalHealth> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<MentalHealth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MentalHealth::getUserId, userId);
        
        // 添加风险等级筛选
        if (warningLevel != null && !warningLevel.isEmpty()) {
            wrapper.eq(MentalHealth::getWarningLevel, Integer.parseInt(warningLevel));
        }
        
        // 添加日期筛选
        if (startDate != null && !startDate.isEmpty()) {
            LocalDateTime startDateTime = LocalDate.parse(startDate).atStartOfDay();
            wrapper.ge(MentalHealth::getAssessmentDate, startDateTime);
        }
        
        if (endDate != null && !endDate.isEmpty()) {
            LocalDateTime endDateTime = LocalDate.parse(endDate).atTime(23, 59, 59);
            wrapper.le(MentalHealth::getAssessmentDate, endDateTime);
        }
        
        wrapper.orderByDesc(MentalHealth::getAssessmentDate);
        return page(page, wrapper);
    }

    @Override
    public MentalHealth getMentalHealthById(Long id) {
        return getById(id);
    }

    @Override
    public boolean updateMentalHealth(MentalHealth mentalHealth) {
        mentalHealth.setUpdateTime(LocalDateTime.now());
        return updateById(mentalHealth);
    }

    @Override
    public boolean deleteMentalHealth(Long id) {
        return removeById(id);
    }

    @Override
    public Map<String, Object> assessMentalHealth(Long userId, Map<String, Object> assessmentData) {
        try {
            // 解析评估数据
            Map<String, Object> answers = (Map<String, Object>) assessmentData.get("answers");
            Integer age = (Integer) assessmentData.get("age");
            String notes = (String) assessmentData.get("notes");
            
            // 计算各维度评分
            int emotionScore = calculateEmotionScore(answers);
            int behaviorScore = calculateBehaviorScore(answers);
            int socialScore = calculateSocialScore(answers);
            int learningScore = calculateLearningScore(answers);
            
            // 计算综合评分
            int overallScore = (emotionScore + behaviorScore + socialScore + learningScore) / 4;
            
            // 确定情绪状态
            int emotionState = determineEmotionState(emotionScore);
            
            // 确定预警级别
            int warningLevel = determineWarningLevel(overallScore);
            
            // 生成建议
            String suggestions = generateSuggestions(emotionScore, behaviorScore, socialScore, learningScore, age);
            
            // 创建心理健康记录
            MentalHealth mentalHealth = new MentalHealth();
            mentalHealth.setUserId(userId);
            mentalHealth.setAssessmentType(1); // 综合评估
            mentalHealth.setAssessmentDate(LocalDateTime.now());
            mentalHealth.setEmotionState(emotionState);
            mentalHealth.setEmotionScore(emotionScore);
            mentalHealth.setBehaviorScore(behaviorScore);
            mentalHealth.setSocialScore(socialScore);
            mentalHealth.setLearningScore(learningScore);
            mentalHealth.setOverallScore(overallScore);
            mentalHealth.setWarningLevel(warningLevel);
            mentalHealth.setNeedsAttention(warningLevel > 1 ? 1 : 0);
            mentalHealth.setParentConfirmed(0); // 待家长确认
            mentalHealth.setAssessmentDetails(assessmentData.toString());
            mentalHealth.setSuggestions(suggestions);
            
            save(mentalHealth);
            
            // 返回评估结果
            Map<String, Object> result = new HashMap<>();
            result.put("emotionScore", emotionScore);
            result.put("behaviorScore", behaviorScore);
            result.put("socialScore", socialScore);
            result.put("learningScore", learningScore);
            result.put("overallScore", overallScore);
            result.put("warningLevel", warningLevel);
            result.put("suggestions", suggestions);
            result.put("assessmentId", mentalHealth.getId());
            
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, Object> getMentalHealthStatistics(Long userId) {
        LambdaQueryWrapper<MentalHealth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MentalHealth::getUserId, userId);
        
        long totalCount = count(wrapper);
        
        // 统计不同警告级别的数量
        long lowRiskCount = count(wrapper.eq(MentalHealth::getWarningLevel, 0));
        long mildRiskCount = count(wrapper.eq(MentalHealth::getWarningLevel, 1));
        long moderateRiskCount = count(wrapper.eq(MentalHealth::getWarningLevel, 2));
        long severeRiskCount = count(wrapper.eq(MentalHealth::getWarningLevel, 3));
        
        // 计算平均分数，处理null值情况
        Double emotionScoreResult = baseMapper.selectAvgEmotionScore(userId);
        Double behaviorScoreResult = baseMapper.selectAvgBehaviorScore(userId);
        Double socialScoreResult = baseMapper.selectAvgSocialScore(userId);
        Double learningScoreResult = baseMapper.selectAvgLearningScore(userId);
        Double overallScoreResult = baseMapper.selectAvgOverallScore(userId);
        
        double avgEmotionScore = emotionScoreResult != null ? emotionScoreResult : 0.0;
        double avgBehaviorScore = behaviorScoreResult != null ? behaviorScoreResult : 0.0;
        double avgSocialScore = socialScoreResult != null ? socialScoreResult : 0.0;
        double avgLearningScore = learningScoreResult != null ? learningScoreResult : 0.0;
        double avgOverallScore = overallScoreResult != null ? overallScoreResult : 0.0;
        
        // 统计最近30天的评估次数
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        long recentCount = count(wrapper.ge(MentalHealth::getAssessmentDate, thirtyDaysAgo));
        
        // 获取趋势数据
        List<Map<String, Object>> trendData = getTrendData(userId, 30);
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalCount", totalCount);
        statistics.put("lowRiskCount", lowRiskCount);
        statistics.put("mediumRiskCount", mildRiskCount + moderateRiskCount);
        statistics.put("highRiskCount", severeRiskCount);
        statistics.put("avgEmotionScore", avgEmotionScore);
        statistics.put("avgBehaviorScore", avgBehaviorScore);
        statistics.put("avgSocialScore", avgSocialScore);
        statistics.put("avgLearningScore", avgLearningScore);
        statistics.put("avgOverallScore", avgOverallScore);
        statistics.put("recentCount", recentCount);
        statistics.put("trendData", trendData);
        
        return statistics;
    }

    /**
     * 获取趋势数据
     */
    private List<Map<String, Object>> getTrendData(Long userId, int days) {
        List<Map<String, Object>> trendData = new ArrayList<>();
        LocalDateTime endDate = LocalDateTime.now();
        LocalDateTime startDate = endDate.minusDays(days);
        
        LambdaQueryWrapper<MentalHealth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MentalHealth::getUserId, userId)
               .ge(MentalHealth::getAssessmentDate, startDate)
               .le(MentalHealth::getAssessmentDate, endDate)
               .orderByAsc(MentalHealth::getAssessmentDate);
        
        List<MentalHealth> assessments = list(wrapper);
        
        for (MentalHealth assessment : assessments) {
            Map<String, Object> dataPoint = new HashMap<>();
            dataPoint.put("date", assessment.getAssessmentDate().toLocalDate().toString());
            dataPoint.put("emotionScore", assessment.getEmotionScore());
            dataPoint.put("behaviorScore", assessment.getBehaviorScore());
            dataPoint.put("socialScore", assessment.getSocialScore());
            dataPoint.put("learningScore", assessment.getLearningScore());
            dataPoint.put("overallScore", assessment.getOverallScore());
            trendData.add(dataPoint);
        }
        
        return trendData;
    }

    @Override
    public String getMentalHealthAdvice(Integer assessmentType, Integer score) {
        if (score >= 80) {
            return "建议您寻求专业心理咨询师的帮助，当前状态需要重点关注。";
        } else if (score >= 60) {
            return "建议您多与家人朋友交流，适当进行放松活动。";
        } else {
            return "您的心理状态良好，继续保持积极乐观的心态。";
        }
    }

    @Override
    public List<Map<String, Object>> getEmotionTrend(Long userId, Integer days) {
        return getTrendData(userId, days);
    }

    @Override
    public boolean confirmAssessment(Long id) {
        MentalHealth mentalHealth = getById(id);
        if (mentalHealth != null) {
            mentalHealth.setParentConfirmed(1);
            mentalHealth.setUpdateTime(LocalDateTime.now());
            return updateById(mentalHealth);
        }
        return false;
    }

    /**
     * 计算情绪评分
     */
    private int calculateEmotionScore(Map<String, Object> answers) {
        int score = 0;
        int count = 0;
        
        // 情绪相关问题 (5个问题)
        for (int i = 0; i < 5; i++) {
            Object answer = answers.get("emotionAnswers[".concat(String.valueOf(i)).concat("]"));
            if (answer instanceof Integer) {
                score += ((Integer) answer).intValue() * 20; // 转换为0-100分
                count++;
            }
        }
        
        return count > 0 ? score / count : 50;
    }

    /**
     * 计算行为评分
     */
    private int calculateBehaviorScore(Map<String, Object> answers) {
        int score = 0;
        int count = 0;
        
        // 行为相关问题 (4个问题)
        for (int i = 0; i < 4; i++) {
            Object answer = answers.get("behaviorAnswers[".concat(String.valueOf(i)).concat("]"));
            if (answer instanceof Integer) {
                score += ((Integer) answer).intValue() * 20;
                count++;
            }
        }
        
        return count > 0 ? score / count : 50;
    }

    /**
     * 计算社交评分
     */
    private int calculateSocialScore(Map<String, Object> answers) {
        int score = 0;
        int count = 0;
        
        // 社交相关问题 (4个问题)
        for (int i = 0; i < 4; i++) {
            Object answer = answers.get("socialAnswers[".concat(String.valueOf(i)).concat("]"));
            if (answer instanceof Integer) {
                score += ((Integer) answer).intValue() * 20;
                count++;
            }
        }
        
        return count > 0 ? score / count : 50;
    }

    /**
     * 计算学习评分
     */
    private int calculateLearningScore(Map<String, Object> answers) {
        int score = 0;
        int count = 0;
        
        // 学习相关问题 (4个问题)
        for (int i = 0; i < 4; i++) {
            Object answer = answers.get("learningAnswers[".concat(String.valueOf(i)).concat("]"));
            if (answer instanceof Integer) {
                score += ((Integer) answer).intValue() * 20;
                count++;
            }
        }
        
        return count > 0 ? score / count : 50;
    }

    /**
     * 确定情绪状态
     */
    private int determineEmotionState(int emotionScore) {
        if (emotionScore >= 80) return 1; // 开心
        if (emotionScore >= 60) return 2; // 平静
        if (emotionScore >= 40) return 3; // 难过
        if (emotionScore >= 20) return 4; // 愤怒
        return 5; // 焦虑
    }

    /**
     * 确定预警级别
     */
    private int determineWarningLevel(int overallScore) {
        if (overallScore >= 80) return 0; // 低风险
        if (overallScore >= 60) return 1; // 轻度
        if (overallScore >= 40) return 2; // 中度
        return 3; // 重度
    }

    /**
     * 生成个性化建议
     */
    private String generateSuggestions(int emotionScore, int behaviorScore, int socialScore, int learningScore, Integer age) {
        StringBuilder suggestions = new StringBuilder();
        
        // 情绪建议
        if (emotionScore < 60) {
            suggestions.append("情绪管理：建议通过运动、音乐、绘画等方式来调节情绪，培养积极的心态。");
        }
        if (emotionScore < 40) {
            suggestions.append("情绪支持：建议寻求专业心理咨询师的帮助，学习情绪管理技巧。");
        }
        
        // 行为建议
        if (behaviorScore < 60) {
            suggestions.append("行为引导：建议制定明确的规则和奖励机制，帮助孩子建立良好的行为习惯。");
        }
        if (behaviorScore < 40) {
            suggestions.append("行为干预：建议寻求行为治疗师的帮助，制定个性化的行为改善计划。");
        }
        
        // 社交建议
        if (socialScore < 60) {
            suggestions.append("社交技能：建议多参加集体活动，培养孩子的社交技能和团队合作能力。");
        }
        if (socialScore < 40) {
            suggestions.append("社交支持：建议寻求社交技能训练，帮助孩子建立良好的人际关系。");
        }
        
        // 学习建议
        if (learningScore < 60) {
            suggestions.append("学习方法：建议调整学习方法和环境，培养孩子的学习兴趣和专注力。");
        }
        if (learningScore < 40) {
            suggestions.append("学习支持：建议寻求学习障碍评估，制定个性化的学习计划。");
        }
        
        // 年龄建议
        if (age != null) {
            if (age < 10) {
                suggestions.append("对于学龄前儿童，建议家长更多地参与孩子的游戏和活动。");
            } else if (age >= 10 && age < 18) {
                suggestions.append("对于青少年，建议家长关注孩子的兴趣爱好和心理变化。");
            } else {
                suggestions.append("对于成年人，建议关注孩子的职业发展和个人兴趣。");
            }
        }
        
        return suggestions.toString();
    }
}